package com.lance.answer.question_export;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.lance.answer.dto.Item;
import com.lance.answer.gui.answer.DealJsonString;
import com.lance.answer.gui.answer.Question;
import com.lance.answer.gui.answer.Util;
import com.lance.answer.question_answer.XjCourseInfo;
import com.lance.answer.util.HttpUtil;
import com.lance.answer.util.XinJiangUtil;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.io.File;
import java.time.Duration;
import java.util.*;

/**
 * 2021-10-26 获取一体化某个课程
 */
public class GetSingleAnswersByTeacherJson {


    public static List<WebElement> findElementsByCssSelector(WebDriver driver, String cssSelector, long seconds) {
        return (new WebDriverWait(driver, Duration.ofSeconds(seconds)).until((ExpectedCondition<List<WebElement>>)
                d -> d.findElements(By.cssSelector(cssSelector))));
    }

    public static WebElement findElementByCssSelector(WebDriver driver, String cssSelector, long seconds) {
        return (new WebDriverWait(driver, Duration.ofSeconds(seconds)).until((ExpectedCondition<WebElement>)
                d -> d.findElement(By.cssSelector(cssSelector))));
    }

    public static void main(String[] args) throws Exception {

        WebDriver driver = Util.getDriver(null);
        String url = "https://xjskk.open.com.cn/teacherspace-auth/#/login";
        // 打开指定的网站
        driver.get(url);
        Thread.sleep(200);

        for (WebElement we : driver.findElements(By.className("el-input__inner"))) {
            if ("text".equals(we.getAttribute("type"))) {
                we.sendKeys(new String[]{"lijunj"});
            }
            if ("password".equals(we.getAttribute("type"))) {
                we.sendKeys(new String[]{"lijunj"});
            }
        }
        driver.findElement(By.cssSelector("button[class='el-button login-ruleForm-btn el-button--primary']")).click();

        // 进入课程观察员角色的页面

        findElementByCssSelector(driver, "div[title='课程观察员']", 20).click();

        Thread.sleep(5000);


        Set<Cookie> cookies = driver.manage().getCookies();
        String studentSpaceProfile = Util.getStudentSpaceProfile(cookies);
        String authorization = Util.getAuthorization(cookies);
        // 初始化头部
        Map<String, String> heads = XinJiangUtil.initHttpHeads(studentSpaceProfile, authorization);

        String cookie = Util.getCookie(cookies);


        //: https://xjskk.open.com.cn/api/teacher/teacher-space-service/courses?pageNumber=6&pageSize=20&status=0&semesterId=23


        boolean hasNext = true;

        List<XjCourseInfo> xjCourseInfoList = new LinkedList<>();
        List<XjCourseInfo.ContentDTO.ItemsDTO> itemsDTOS = new LinkedList<>();

//        int openCourseId = 33539;
//        String subjectName = "个人与团队管理";
        int openCourseId = 33331;
        String subjectName = "医学生物化学";



            driver.navigate().refresh();
            Thread.sleep(4000);
            cookies = driver.manage().getCookies();
            // 初始化头部
            cookie = Util.getCookie(cookies);

            List<Question> questions = Lists.newArrayList();
            questions.clear();
            int pageIndex = 1;
            boolean hashNextPage = true;
            while (hashNextPage) {
                try {

                    String postUrl = "https://xjskk.open.com.cn/api/teacher/teacher-space-service/testQuestions";
                    System.err.println("postUrl:" + postUrl);


                    Map<String, Object> data = Maps.newHashMap();
                    //  jsonObject.put("openCourseId",openCourseId);
                    data.put("openCourseId", openCourseId);
                //    data.put("openCourseId", Long.parseLong("30913"));
                    data.put("pageNumber", pageIndex);
                    data.put("pageSize", 20);
                    String result = HttpUtil.post(postUrl, data, cookie, heads);
                    System.err.println("result:::" + result);
                    YiTiHuaSimpileAnswerInfo yiTiHuaSimpileAnswerInfo = JSONObject.parseObject(result, YiTiHuaSimpileAnswerInfo.class);

                    // 题目的总数；
                    int total = yiTiHuaSimpileAnswerInfo.getContent().getTotal();
                    // 总页数
                    int page = yiTiHuaSimpileAnswerInfo.getContent().getPage();

                    String itemBankId = yiTiHuaSimpileAnswerInfo.getContent().getItemBankId();
                    List<String> idList = Lists.newArrayList();

                    for (YiTiHuaSimpileAnswerInfo.ContentDTO.ItemsDTO items : yiTiHuaSimpileAnswerInfo.getContent().getItems()) {
                        idList.add(items.getI1());
                    }

                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("itemBankId", itemBankId);
                    jsonObject.put("idList", idList);
                    System.err.println("json:" + jsonObject.toJSONString());

                    String postUrl2 = "https://xjskk.open.com.cn/api/teacher/teacher-space-service/testQuestions/questionWithoutAnswer";
                    String questionDetails = HttpUtil.postJson(postUrl2, jsonObject, cookie, heads);
                    System.err.println("questionDetails:" + questionDetails);

                    QuestionDetail questionDetail = JSONObject.parseObject(questionDetails, QuestionDetail.class);


                    for (QuestionDetail.ContentDTO contentDTO : questionDetail.getContent()) {
                        Question question = new Question();
                        question.setTitle(contentDTO.getI2());
                        question.setScore(contentDTO.getI9()+0.0);
                        int i3 = contentDTO.getI3();
                        question.setQuestionType(i3);


                        if(i3<=3){
                            if (i3 == 1) {
                                question.setQuestionTypeDesc("单选题");
                            } else if (i3 == 2) {
                                question.setQuestionTypeDesc("多选题");
                            } else {
                                question.setQuestionTypeDesc("判断题");
                            }


                            List<Item> items = Lists.newArrayList();
                            question.setItems(items);
                            List<String> answers = contentDTO.getI6();
                            for (String answer : answers) {
                                Item item = new Item(answer, "");
                                items.add(item);
                            }

                            // 正确的答案所在的位置
                            List<String> correctIndex = contentDTO.getI7();
                            List<String> correctList = Lists.newArrayList();
                            for (String cIndex : correctIndex) {
                                int index = Integer.parseInt(cIndex);
                                if(i3!=3){
                                    correctList.add(answers.get(index));
                                }
                                else {
                                    if(answers.get(index).equals("0")){
                                        correctList.add("对");
                                    }
                                    if(answers.get(index).equals("1")){
                                        correctList.add("错");
                                    }
                                }
                            }
                            String[] correctArray = new String[]{};
                            correctArray = correctList.toArray(correctArray);
                            System.err.println("correctArray:" + JSON.toJSONString(correctArray));
                            question.setCorrectArray(correctArray);

                            System.err.println("????????????111:"+JSON.toJSONString(question.getCorrectArray()));
                        }
                       else {
                            if (i3 == 4) {
                                question.setQuestionTypeDesc("填空题");
                            } else {
                                question.setQuestionTypeDesc("简答题");
                            }
                            // 正确的答案所在的位置
                            List<String> answers = contentDTO.getI6();
                            String[] correctArray = new String[]{};
                            correctArray = answers.toArray(correctArray);
                            question.setCorrectArray(correctArray);
                        }

                        questions.add(question);

                        System.err.println("??????????????222:"+JSON.toJSONString(question.getCorrectArray()));
                    }
                    FileUtils.write(new File("D:\\新疆一体化1026\\" + subjectName + "\\" + pageIndex + ".json"), questionDetails);

                    pageIndex++;
                    if (pageIndex > page) {
                        hashNextPage = false;
                    }


                } catch (Exception e) {
                    e.printStackTrace();
                } finally {

                }
            }


            while (hashNextPage) {
                Thread.sleep(5000);
            }

            //   Collections.sort(questions);
            List<Map<String, Object>> answers = new ArrayList<>();
            for (Question question : questions) {
                String title = question.getTitle();
                title = Util.dealContent(title);
                Map<String, Object> answerMap = new HashMap<>();
                answerMap.put("questionType", question.getQuestionType());
                answerMap.put("answerType", "click");
                answerMap.put("questionTypeDesc", question.getQuestionTypeDesc());
                answerMap.put("questionTitle", DealJsonString.delHTMLTag(title));
                answerMap.put("questionCode", question.getQuestionCode());
                answerMap.put("items", question.getItems());
                answerMap.put("answers", question.getCorrectArray());
                System.err.println("question.getCorrectArray():"+JSON.toJSONString(question.getCorrectArray()));
                answerMap.put("score", question.getScore());
                answers.add(answerMap);
            }

            FileUtils.write(new File("D:\\新疆一体化1026\\" + subjectName + "\\"+subjectName+".json"), JSONObject.toJSONString(answers, SerializerFeature.PrettyFormat), "utf-8");

            Thread.sleep(1000);
         //   driver.close();
          //  Util.switchToFirst(driver);


        System.err.println("end........");
//        driver.quit();


    }


}
